package cn.edu.sgu.www.mhxysy.filter;

import cn.edu.sgu.www.mhxysy.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器
 * @author heyunlin
 * @version 1.0
 */
@WebFilter(filterName = "loginFilter", urlPatterns = {"/", "/html/*", "/index.html"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession();

        Object obj = session.getAttribute("user");
        User user = obj == null ? null : (User) obj;

        if (user == null) {
            HttpServletResponse response = (HttpServletResponse) resp;

            response.sendRedirect("/login.html");
        } else {
            chain.doFilter(req, resp); // 放行
        }
    }

}